<template>
  <div class="edit-category-container">
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="header-box">
        <span class="header-title">编辑分类</span>
      </div>

      <el-form
        :model="formData"
        label-width="100px"
        class="form-container"
        size="small"
      >
        <el-form-item label="所属小区" prop="communityId" required>
          <el-select
            v-model="formData.communityName"
            placeholder="请选择小区"
            class="compact-input"
            @change="handleCommunityChange"
            :loading="loading.community"
          >
            <el-option
              v-for="item in communityOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类名称" required>
          <el-input
            v-model="formData.categoryName"
            placeholder="请输入分类名称"
            class="compact-input"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="描述">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="2"
            placeholder="请输入分类描述"
            class="compact-input"
          >
          </el-input>
        </el-form-item>

        <el-form-item label="分类图标" required>
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :before-upload="beforeUpload"
            :on-change="handleFileChange"
            ref="upload"
          >
            <img v-if="formData.url" :src="formData.url" class="avatar" />
            <div v-else class="upload-placeholder">
              <i class="el-icon-plus avatar-uploader-icon"></i>
              <div class="upload-text">点击上传图标</div>
            </div>
          </el-upload>
          <div class="el-upload__tip">
            请上传分类图标（格式限制：JPG、PNG），图片大小不超过5M
          </div>
        </el-form-item>

        <el-form-item label="是否显示">
          <el-radio-group
            v-model="formData.isDelete"
            class="custom-radio-group"
          >
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态">
          <el-switch
            v-model="formData.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
          >
          </el-switch>
          <span class="status-text">{{
            formData.status === 1 ? "启用" : "禁用"
          }}</span>
        </el-form-item>
      </el-form>

      <div class="button-group">
        <el-button type="primary" @click="handleUpdate" :loading="saving">
          <i class="el-icon-check"></i>
          保存
        </el-button>
        <el-button @click="handleCancel">
          <i class="el-icon-back"></i>
          返回
        </el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      categoryId: null,
      formData: {
        communityId: "",
        communityName: "",
        categoryName: "",
        remark: "",
        url: "",
        iconFile: null,
        isDelete: 1,
        status: 1,
      },
      originalImageUrl: "", // 存储原始图片URL
      imageFile: null, // 存储单张图片文件对象
      imageChanged: false, // 标记图片是否被更改
      saving: false,
      communityOptions: [],
      loading: {
        community: false,
        category: false
      }
    };
  },

  created() {
    // 获取路由参数中的ID
    this.categoryId = this.$route.query.id;
    if (!this.categoryId) {
      this.$message.error('缺少分类ID参数');
      this.$router.go(-1);
      return;
    }
    
    // 页面加载时获取小区数据
    this.fetchCommunityData();
    
    // 获取分类详情
    this.fetchCategoryDetail();
  },
  
  methods: {
    // 获取小区数据
    fetchCommunityData() {
      this.loading.community = true;
      // 调用API获取小区数据
      this.$axios.get('/api/infrastructure-server/community/queryAll')
        .then(response => {
          if (response.data && response.data.code === 200) {
            this.communityOptions = response.data.data.map(item => {
              return { value: item.id, label: item.name };
            });
          } else {
            this.$message.error(response.data.msg || '获取小区列表失败');
          }
        })
        .catch(error => {
          console.error('获取社区列表错误:', error);
          this.$message.error('网络异常，获取小区列表失败');
        })
        .finally(() => {
          this.loading.community = false;
        });
    },
    
    // 获取分类详情
    fetchCategoryDetail() {
      this.loading.category = true;
      this.$axios.get(`/api/patrol-server/patrolCategory/getById/${this.categoryId}`)
        .then(response => {
          if (response.data && response.data.code === 200) {
            // 填充表单数据
            const categoryData = response.data.data;
            this.formData = {
              ...categoryData,
              communityId: categoryData.communityId,
              communityName: categoryData.communityName,
              // 确保布尔值正确设置
              isDelete: categoryData.isDelete || 1,
              status: categoryData.status || 1
            };
            
            // 保存原始图片URL
            this.originalImageUrl = categoryData.url;
          } else {
            this.$message.error(response.data.msg || '获取分类详情失败');
            setTimeout(() => {
              this.$router.go(-1);
            }, 1500);
          }
        })
        .catch(error => {
          console.error('获取分类详情错误:', error);
          this.$message.error('网络异常，获取分类详情失败');
          setTimeout(() => {
            this.$router.go(-1);
          }, 1500);
        })
        .finally(() => {
          this.loading.category = false;
        });
    },

    // 处理小区选择变更
    handleCommunityChange(val) {
      // 设置小区名称
      const selected = this.communityOptions.find(item => item.value === val);
      if (selected) {
        this.formData.communityName = selected.label;
      }
    },

    // 上传前的验证
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG && !isPNG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },

    // 处理文件变更
    handleFileChange(file) {
      // 保存文件对象
      this.imageFile = file.raw;
      this.imageChanged = true;
      
      // 设置预览
      this.setPreviewImage(file.raw);
    },

    // 设置预览图片
    setPreviewImage(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.formData.url = e.target.result;
      }
      reader.readAsDataURL(file);
    },

    // 上传图片到服务器
    uploadImage() {
      if (!this.imageFile) {
        // 如果图片没有变更，使用原始URL
        if (!this.imageChanged && this.originalImageUrl) {
          return Promise.resolve(this.originalImageUrl);
        }
        return Promise.reject(new Error('没有选择图片'));
      }

      const formData = new FormData();
      formData.append('file', this.imageFile);
      
      return this.$axios.post('api/patrol-server/patrolCategory/uploadIcon', formData)
      .then(response => {
        if (response.data && response.data.code === 200) {
          return response.data.data;
        } else {
          throw new Error(response.data.msg || '上传失败');
        }
      });
    },

    async handleUpdate() {
      // 避免重复提交
      if (this.saving) return;
      
      // 表单验证
      if (!this.formData.communityId) {
        this.$message({
          message: "请选择所属小区",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      
      if (!this.formData.categoryName) {
        this.$message({
          message: "请输入分类名称",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      
      // 检查是否有图片
      if (!this.formData.url && !this.imageFile) {
        this.$message({
          message: "请上传分类图标",
          type: "warning",
          duration: 2000,
        });
        return;
      }
      
      this.saving = true;
      
      try {
        // 如果图片有变更，上传新图片
        let imageUrl = this.originalImageUrl;
        if (this.imageChanged && this.imageFile) {
          imageUrl = await this.uploadImage();
        }
        
        // 更新表单数据中的图片URL
        this.formData.url = imageUrl;
        
        // 提交更新
        const updateData = {
          ...this.formData,
          id: this.categoryId
        };
        
        const response = await this.$axios.post('/api/patrol-server/patrolCategory/update', updateData);
        
        if (response.data && response.data.code === 200) {
          this.$message({
            message: "更新成功",
            type: "success",
            duration: 2000,
          });
          setTimeout(() => {
            this.$router.go(-1);
          }, 1000);
        } else {
          this.$message.error(response.data.msg || '更新失败');
        }
      } catch (error) {
        console.error('更新分类失败:', error);
        this.$message.error(error.message || '更新失败');
      } finally {
        this.saving = false;
      }
    },

    handleCancel() {
      this.$router.go(-1);
    },
  },

};
</script>

<style scoped>
.edit-category-container {
  padding: 20px;
  width: 100%;
  max-width: 650px;
  margin: 0 auto;
}

.box-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.box-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.08);
}

.header-box {
  display: flex;
  align-items: center;
}

.header-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  position: relative;
  padding-left: 12px;
}

.header-title::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 16px;
  width: 4px;
  background-color: #409eff;
  border-radius: 2px;
}

.form-container {
  margin: 12px 0;
  padding: 0 10px;
}

/* 紧凑型输入框样式 */
.compact-input {
  width: 280px !important;
  transition: all 0.3s ease;
}

.compact-input .el-input__inner {
  height: 32px;
  line-height: 32px;
  font-size: 13px;
}

.compact-input .el-textarea__inner {
  font-size: 13px;
  padding: 8px 10px;
}

.compact-input:hover,
.compact-input:focus {
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.2);
}

.el-form-item {
  margin-bottom: 16px;
}

/* 图片上传相关样式 */
.avatar-uploader .el-upload {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
  background-color: rgba(64, 158, 255, 0.05);
  transform: scale(1.02);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.upload-placeholder {
  width: 140px;
  height: 140px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f7f9fc;
  background-image: linear-gradient(
      90deg,
      rgba(220, 226, 233, 0.3) 1px,
      transparent 1px
    ),
    linear-gradient(rgba(220, 226, 233, 0.3) 1px, transparent 1px);
  background-size: 10px 10px;
}

.avatar-uploader-icon {
  font-size: 30px;
  color: #8c939d;
}

.upload-text {
  margin-top: 10px;
  color: #8c939d;
  font-size: 14px;
}

.avatar {
  width: 140px;
  height: 140px;
  display: block;
  object-fit: cover;
  border-radius: 4px;
}

.el-upload__tip {
  font-size: 12px;
  color: #909399;
  line-height: 1.5;
  margin-top: 8px;
}

.status-text {
  margin-left: 10px;
  font-size: 14px;
  color: #606266;
}

.custom-radio-group {
  display: flex;
  align-items: center;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

.button-group .el-button {
  margin: 0 15px;
  padding: 8px 20px;
  min-width: 100px;
  font-size: 13px;
  transition: all 0.3s ease;
}

.button-group .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.button-group .el-button i {
  margin-right: 5px;
}

@media screen and (max-width: 768px) {
  .edit-category-container {
    padding: 10px;
  }
  
  .form-container {
    padding: 0;
  }
  
  .compact-input {
    width: 100% !important;
  }
}
</style>